<template>
  <div>

    <el-dialog :title="formTitle" :visible.sync="dialogFormVisible" class="project-dialog">
      <div v-loading="dialogLoading">
        <el-form :model="form">
          <el-form-item label="标题" :label-width="formLabelWidth">
            <el-input v-model="form.title" auto-complete="off" placeholder="请输入标题"></el-input>
          </el-form-item>
          <el-form-item label="描述" :label-width="formLabelWidth">
            <el-input v-model="form.desc" auto-complete="off" placeholder="请输入描述内容"></el-input>
          </el-form-item>
          <el-form-item label="成员" :label-width="formLabelWidth">
            <el-select v-model="selectedMemberList" multiple filterable placeholder="请选择成员" :style="{'width': '100%','padding-right':selectedProjectObj? '80px':'0'}">
              <el-option v-for="(item,index) in memberList" :key="index" :label="item.nname||item.username" :value="item.personCode" v-if="item.personCode!=((adminMember.fuid||0)+'_'+(adminMember.pid||0))">
              </el-option>
            </el-select>
            <el-button type="primary" style="position: absolute;right: 0;top:0;" @click="inviteMember" v-show="selectedProjectObj">邀请</el-button>
          </el-form-item>
        </el-form>
        <div class="tag-container">
          <h6 style="margin:0 0 15px 0;">标签</h6>
          <div class="tagTmpContainer">
            <div v-for="(item,index) in tagTmpsArr">
              <el-checkbox v-model="item.checked" @change="tapTmpChange(index)" style="width:100%;white-space: normal;">{{item.str}}</el-checkbox>
            </div>
          </div>
          <el-tag :key="tag.key" v-for="tag in dynamicTags" :closable="true" :close-transition="false" @close="handleClose(tag)">
            {{tag.name}}
          </el-tag>
          <el-input class="input-new-tag" v-if="inputVisible" v-model="inputValue" ref="saveTagInput" size="mini" @keyup.enter.native="handleInputConfirm"
            @blur="handleInputConfirm">
          </el-input>
          <el-button v-else class="button-new-tag" size="small" @click="showInput">添加标签 </el-button>
        </div>
        <div class="tag-container">
          <h6 style="margin:15px 0;">所有标签</h6>
          <div class="all-tag">

            <span v-for="(item,index) in allTags" :class="item.active?'active':''" @click="allTagClick(index)" v-if="initSystemTags.indexOf(item.key)<0">{{item.name||item.key}}</span>
          </div>
        </div>

      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false" size="small">取 消</el-button>
        <el-button type="primary" @click="saveFun()" size="small">保 存</el-button>
      </div>

    </el-dialog>

    <el-dialog width="30%" title="邀请成员" :visible.sync="inviteDialogVisible" style="text-align: center;">
      <el-form :model="form">
        <el-form-item>
          <vue-q-art :config="qartConfig"></vue-q-art>
        </el-form-item>
      </el-form>
      <el-form :model="form">
        <el-form-item>
          链接
          <el-input v-model="qartConfig.value" readonly style="display: inline-block;width:50%;margin:0 10px"></el-input>
          <el-button type="primary" style="color:#fff" id="clip" :data-clipboard-text="qartConfig.value">复制</el-button>
          <el-button type="primary" style="color:#fff" @click="refreshInviteUrl">刷新</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
  import Clipboard from 'clipboard'
  import VueQArt from 'vue-qart'
  import pinyin from '../../../static/z39pc/js/pinyin.js'
  import api from '../../api';
  import {
    taskAndTag
  } from "../../common/mixin";
  import {
    mixinPc
  } from "../../common/mixinPc";
  import {
    mapState,
    mapActions
  } from 'vuex'
  var initPage = function () {

  }
  export default {
    name: 'addProjectDialog',
    data() {
      return {
        inviteDialogVisible: false,
        adminMember: '',
        dialogFormVisible: false,
        dialogLoading: false,
        dynamicTags: [],
        inputVisible: false,
        inputValue: '',
        allTags: [],
        formTitle: '添加项目',
        form: {
          title: '',
          desc: ''
        },
        formLabelWidth: '40px',
        selectedMemberList: [],
        selectedProjectObj: '',
        proTagTemp: {}, //项目自带的模板
        proMemberList: [], //项目自带的成员列表
        tagTmpsArr: [],
        memberList: [],
        memberListDic: {},
        qartConfig: {
          value: '',
          imagePath: './static/z39pc/images/timg.png',
          filter: 'color'
        },
      }

    },
    components: {
      VueQArt
    },
    mixins: [taskAndTag, mixinPc],
    computed: {
      ...mapState({
        uid: state => state.vux.uid,
        tagitems: state => state.z39.tagitems,
        tagitemDic: state => state.z39.tagitemDic,
        tagtmps: state => state.z39.tagtmps,
        //memberList: state => state.z39.members,
        projects: state => state.z39.projects,
      })
    },
    watch: {
      'tagitems': function () {
        this.allTags = this.tagitems.map(function (item, index, arr) {
          var item1 = Object.assign({}, item)
          item1['active'] = false;
          return item1;
        })
      },
      "allTags": {
        handler() {

        },
        deep: true,
      },
    },
    created() {
      this.allTags = this.tagitems.map(function (item, index, arr) {
        var item1 = Object.assign({}, item)
        item1['active'] = false
        return item1;
      })
    },
    methods: {
      showDialog: function (item) {
        var _this = this;
        this.resetDialog()
        this.dialogFormVisible = true;
        this.selectedProjectObj = '';
        this.formTitle = "添加项目"
      },
      editDialog: function (pid) {
        this.resetDialog()
        this.formTitle = "编辑项目"
        var _this = this;
        if (!pid) {
          this.$message({
            message: '请先选择项目',
            type: 'warning'
          });
          return;
        }
        //找出项目
        this.projects.forEach(function (item) {
          if (item.id == pid) {
            _this.selectedProjectObj = item;
            _this.form.title = item.title;
            _this.form.desc = item.desc;
          }
        })
        //找出项目的模板

        //获取项目信息
        api.projectGet({
          id: pid,
          setting: 1
        }).then(data => {
          if (data.errno == 0) {
            //成员
            data.data.members && data.data.members.forEach(function (item) {
              _this.proMemberList.push(item.id);
              if (item.admin != null) {
                _this.adminMember = Object.assign({}, item)
              } else {
                _this.selectedMemberList.push((item.fuid || 0) + '_' + (item.pid || 0));
              }
              item.personCode = (item.fuid || 0) + '_' + (item.pid || 0)
              _this.memberListDic[item.personCode] = item;
              _this.memberList.push(item)
            })
            //模板
            var proTagTemp = data.data.tagtmp;
            if (proTagTemp.tmp) {
              proTagTemp.tmp.split(',').forEach(function (item) {
                _this.dynamicTags.push({
                  isExsist: false,
                  name: _this.tagitemDic[item],
                  val: item
                })
              })
            }
            _this.proTagTemp = proTagTemp;
          }
        })
        this.dialogFormVisible = true;
      },
      resetDialog: function () {
        var _this = this;
        this.form.title = '';
        this.form.desc = '';
        this.adminMember = '';
        this.selectedMemberList = [];
        this.proMemberList = [];
        this.inputVisible = false;
        this.dynamicTags = [];
        this.allTags.forEach(function (item, index, arr) {
          item['active'] = false;
        })
        //显示模板
        api.tagTmpGet().then(data => {
          if (data.errno == 0) {
            var tagArr = data.data;
            tagArr = tagArr || [];
            tagArr.forEach(function (item1) {
              var arrStr = [];
              item1.tmp && item1.tmp.split(',').forEach(function (item2) {
                _this.tagitemDic[item2] && arrStr.push(_this.tagitemDic[item2])
              })
              item1.str = arrStr.join('，');
              item1.checked = false;
            })
            _this.tagTmpsArr = tagArr;
          }
        })
        //显示成员列表
        api.friends().then(data => {
          if (data.errno == 0) {
            _this.memberList = data.data.map(function (item) {
              item.personCode = item.fuid + '_' + item.pid;

              _this.memberListDic[item.personCode] = item;
              if (item.fuid == null && item.pid == null) {

              }
              return item
            })
            console.log(_this.memberList)
          }
        })
      },
      //修改选择tagtmp模板
      tapTmpChange(index) {
        if (this.tagTmpsArr[index].checked) {
          this.tagTmpsArr.forEach(function (item, i) {
            if (i != index) {
              item.checked = false;
            }
          })
        }
      },
      //所有标签点击
      allTagClick: function (index) {
        //防止重复添加
        var _this = this;
        var hasKey = this.dynamicTags.some(function (item) {
          return item.val == _this.allTags[index].key;
        });
        if (hasKey) {
          this.$message({
            message: '标签已存在',
            type: 'warning'
          });
          return;
        }
        this.allTags[index].active = !this.allTags[index].active;
        var item = {
          val: this.allTags[index].key,
          name: this.allTags[index].name,
          isExsist: true
        }
        if (this.allTags[index]['active']) {

          this.dynamicTags.push(item)
        } else {
          this.dynamicTags = this.dynamicTags.filter(function (item) {
            return item.val != _this.allTags[index].key;
          })
        }
      },
      //保存
      saveFun: function () {
        var _this = this;
        if (!this.form.title) {
          this.showNotice('请输入标题', 'warning');
          return;
        }
        if (this.form.title.length > 15) return this.showNotice('标题最长15字', 'warning');
        if (this.form.desc.length > 100) return this.showNotice('描述最长100字', 'warning');

        //成员列表参数
        var memberParams = [];

        this.selectedMemberList.forEach(function (item) {
          memberParams.push({
            nname: _this.memberListDic[item]['nname'],
            pid: _this.memberListDic[item].pid,
            uid: _this.memberListDic[item].fuid || _this.memberListDic[item].pid,
            gid: _this.selectedProjectObj ? _this.selectedProjectObj.gid : '',
          })
        })
        if (this.adminMember) {
          memberParams.unshift({
            nname: this.adminMember['nname'],
            pid: this.adminMember.pid,
            uid: this.adminMember.fuid || this.adminMember.pid,
            gid: this.selectedProjectObj ? this.selectedProjectObj.gid : '',
          })
        }
        //编辑模式
        this.dialogLoading = true;
        //如果选中标签模板，那么就用标签模板的
        var selectedTagTemp = '';
        var addTagsArrLast = []; //需要添加的标签列表

        this.tagTmpsArr.forEach(function (item) {
          if (item.checked) {
            selectedTagTemp = item;
            //						selectedTagTemp={
            //							id: _this.proTagTemp.id||null,
            //							pid: _this.selectedProjectObj.gid||'',
            //							count: null,
            //							type: 1,
            //							name:'开发' ,
            //							key: 'dev',
            //							tmp: item.tmp
            //						}
          }
        })

        if (!selectedTagTemp) {
          var tmpStr = this.dynamicTags;
          var tagsTmpStrArr = this.dynamicTags.map(function (item) {
            return item.val;
          });
          var addTagsArr = this.dynamicTags.filter(function (item) {
            return item.isExsist == false;
          });

          addTagsArr = addTagsArr.map(function (item) {
            var item1 = {
              value: '',
              name: item.name,
              key: item.val
            }
            return item1;
          })
          //判断添加的标签key在所有标签里面存不存在，如果存在，则不添加

          for (var i = 0; i < addTagsArr.length; i++) {
            var hasKey = false;
            for (var j = 0; j < this.allTags.length; j++) {
              if (this.allTags[j]['key'] == addTagsArr[i]['key']) {
                hasKey = true;
              }
            }
            if (!hasKey) {
              addTagsArrLast.push(addTagsArr[i])
            }
          }
          selectedTagTemp = {
            id: this.proTagTemp.id || null,
            pid: this.selectedProjectObj.gid || '',
            count: null,
            type: 1,
            name: '开发',
            key: 'dev',
            tmp: tagsTmpStrArr.join(',')
          }
        }
        //添加模式
        var proParams = {
          title: this.form.title,
          desc: this.form.desc,
          members: memberParams,
          tmp: selectedTagTemp //添加 的模板
        }
        if (selectedTagTemp) {
          proParams.tmpid = selectedTagTemp.id; //选择模板
        }
        if (proParams.tmpid) {
          proParams.tmp = null;
        }
        console.log("-----")
        console.log(selectedTagTemp)
        console.log(proParams)
        console.log("-----")
        if (addTagsArrLast.length > 0) {
          //如果需要添加新标签
          api.tagitemsAdd({
            tags: addTagsArrLast
          }).then(data => {
            if (data && data.errno == 0) {
              var tagIdArr = data.data;
              var itemsArr = [];
              for (var i = 0; i < tagIdArr.length; i++) {
                itemsArr.push({
                  count: null,
                  id: tagIdArr[i],
                  key: addTagsArrLast[i].key,
                  name: addTagsArrLast[i].name,
                  position: null,
                  type: null,
                  value: null
                })
              }
              _this.$store.commit({
                type: "z39/tagitemsAdd",
                tagitems: itemsArr
              });
              //添加模式
              if (!_this.selectedProjectObj) {
                _this.projectAdd(proParams)
                _this.dialogLoading = false;
                _this.dialogFormVisible = false;
              } else {
                //编辑模式
                this.putProTagTmp(selectedTagTemp)
              }

            } else { //发生错误.
              _this.dialogLoading = false;
              _this.$message({
                message: data.errmsg,
                type: 'error'
              });
            }
          }).catch(result => {
            this.dialogLoading = false;
            return this.$message({
              message: '标签创建失败',
              type: 'warning'
            });
          });
        } else if (!this.selectedProjectObj) {
          _this.projectAdd(proParams)
          _this.dialogLoading = false;
          _this.dialogFormVisible = false;
        } else {
          //增加删除成员,修改标签模板
          _this.projectSet({
            title: this.form.title,
            desc: this.form.desc,
            id: this.selectedProjectObj.gid
          })
          //修改标签模板
          selectedTagTemp.id = this.proTagTemp.id;
          selectedTagTemp.pid = this.selectedProjectObj.gid;
          selectedTagTemp.key = 'dev';
          selectedTagTemp.name = "开发";
          this.putProTagTmp(selectedTagTemp)
          //修改成员
          api.memberDel({
            list: JSON.stringify(_this.proMemberList)
          }).then(data => {
            if (data && data.errno == 0) {
              api.memberAdd({
                list: memberParams
              }).then(data => {
                if (data && data.errno == 0) {

                } else { //发生错误.
                  _this.$message({
                    message: data.errmsg,
                    type: 'error'
                  });
                }
              })
            } else { //发生错误.
              _this.$message({
                message: data.errmsg,
                type: 'error'
              });
            }
          }).catch(result => {
            return this.$message({
              message: '成员设置失败',
              type: 'warning'
            });
          });
        }
      },
      putProTagTmp: function (params) {
        var _this = this;
        api.tagTmpPut(params).then(data => {
          _this.dialogLoading = false;
          if (data && data.errno == 0) {
            _this.dialogFormVisible = false;
            _this.$store.commit({
              type: "z39/updateTagTmps",
              id: params.id,
              tmp: params.tmp,
              key: 'dev'
            });
          } else { //发生错误.
            _this.$message({
              message: data.errmsg,
              type: 'error'
            });
          }
        })
      },
      handleClose(tag) {
        this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1);
      },
      showInput() {
        this.inputVisible = true;
        this.$nextTick(_ => {
          this.$refs.saveTagInput.$refs.input.focus();
        });
      },

      handleInputConfirm() {
        let inputValue = this.inputValue.trim();
        if (inputValue) {
          //					防止重复添加
          var valueText = pinyin.pinyin.getCamelChars(inputValue) + pinyin.pinyin.getFullChars(inputValue);
          if (inputValue.length > 12) {
            this.showNotice('标签长度不能不能超过12个字符', 'warning');
            return;
          }
          if (valueText.length > 25) {
            valueText = valueText.substring(0, 25)
          }
          var hasKey = this.dynamicTags.some(function (item) {
            return item.val == valueText;
          });
          if (!hasKey) {
            this.dynamicTags.push({
              name: inputValue,
              val: valueText,
              isExsist: false
            });
            this.inputVisible = false;
            this.inputValue = '';
          } else {
            this.$message({
              message: '标签已存在',
              type: 'warning'
            });
          }
        } else {
          this.inputVisible = false;
        }

      },
      inviteMember: function () {
        api.invitefriends({
          type: 1,
          xid: this.selectedProjectObj.id,
          iid: this.uid
        }).then(data => {
          if (data && data.errno == 0) {
            this.inviteDialogVisible = true;
            this.qartConfig.value = data.data;
          } else { //发生错误.
            _this.$message({
              message: data.errmsg,
              type: 'error'
            });
          }
        })

      },
      refreshInviteUrl: function () {
        api.invitefriends({
          type: 1,
          xid: this.selectedProjectObj.id,
          refresh: 1,
          iid: this.uid
        }).then(data => {
          if (data && data.errno == 0) {
            this.inviteDialogVisible = true;
            this.qartConfig.value = data.data;
          } else { //发生错误.
            this.$message({
              message: data.errmsg,
              type: 'error'
            });
          }
        })
      }
    },
    mounted() {
      initPage();
      var _this = this;
      const clipboard = new Clipboard('#clip');
      clipboard.on('success', function (e) {
        _this.$message({
          message: '复制成功',
          type: 'success'
        });
      });
    }
  }
</script>

<style>
  .project-dialog .el-form-item {
    margin-bottom: 10px;
  }

  .project-dialog .button-new-tag,
  .project-dialog .input-new-tag {
    margin-left: 10px;
    height: 24px;
    line-height: 22px;
    padding-top: 0;
    padding-bottom: 0;
    width: 80px;
  }

  .project-dialog .tag-container .el-tag+.el-tag {
    margin: 0 0 10px 10px;
  }

  .project-dialog .el-select__input.is-undefined {
    margin-left: 10px;
  }

  .project-dialog .el-button--primary {
    color: #fff;
  }

  .all-tag {
    overflow: hidden;
  }

  .all-tag span {
    padding: 0 5px;
    border-radius: 3px;
    border: 1px solid #aaa;
    float: left;
    margin: 0 10px 5px 0;
    font-size: 12px;
    cursor: pointer;
  }

  .all-tag span.active {
    color: #fff;
    background: #1ba4ff;
    border: 1px solid #1ba4ff;
  }

  .tagTmpContainer {
    margin-bottom: 15px;
    /*padding-left: 20px;*/
  }
</style>